package com.artezio.testapp.controller.ajax;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.artezio.testapp.domain.City;
import com.artezio.testapp.domain.ajax.DataTablesParamModel;
import com.artezio.testapp.service.CityService;
import com.artezio.testapp.service.ajax.DataTablesCityService;
import com.artezio.testapp.service.ajax.DataTablesParamUtility;

import com.google.gson.JsonObject;


@Controller
@RequestMapping(value = "/ajax/datatables")
public class DataTablesController {
	
	private static final Logger logger = LoggerFactory.getLogger(DataTablesController.class);
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private DataTablesCityService dataTablesCityService;
	
	@RequestMapping(value = "/cityDataSource.json", method = RequestMethod.POST)
	public @ResponseBody 
	String getData(HttpServletRequest request, HttpServletResponse response) {
		
	    DataTablesParamModel param = DataTablesParamUtility.getParam(request);    
	    
	    JsonObject jsonResponse = new JsonObject();
		List<City> cityList;
		
		cityList = dataTablesCityService.listCity(param);
		
		//Generate JSON response
		jsonResponse.addProperty("sEcho", param.sEcho);
		jsonResponse.addProperty("iTotalRecords", cityService.getCount());
		jsonResponse.addProperty("iTotalDisplayRecords", cityService.getFilteredCount(param.sSearch));
		jsonResponse.add("aaData", DataTablesCityService.generateJsonArray(cityList));
		
		return jsonResponse.toString();
	}
	
	
}